package com.op.studyingliteapp.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.op.studyingliteapp.R;
import com.op.studyingliteapp.activity.homeactivity.HomeActivity;
import com.op.studyingliteapp.adapter.DropDownAdapter;
import com.op.studyingliteapp.bean.UserBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.database.dao.UserDao;
import com.op.studyingliteapp.task.LoginTask;
import com.op.studyingliteapp.task.LoginTask.LoginCallback;
import com.op.util.IntentUtils;
import com.op.util.SharedPreferenceUtil;
import com.op.util.StringUtils;
import com.op.util.ToastUtils;
import com.op.util.network.NetworkUtils;

public class LoginActivity extends Activity implements LoginCallback {
	private static final String TAG = LoginActivity.class.getSimpleName();
	public static EditText userNumInput, userPwdInput;
	public static ImageButton dropDown;
	private CheckBox autoLogin;
	public static PopupWindow popupWindow;
	private Button login;
	private boolean isDropDownButtonClicked;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		setupViews();
		// 更新autoLogin的状态
		SharedPreferences preferences = SharedPreferenceUtil.getInstance(LoginActivity.this);
		boolean isAutoLogin = preferences.getBoolean(Common.Prefs.IS_AUTO_LOGIN, false);
		isDropDownButtonClicked = preferences.getBoolean(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
		autoLogin.setChecked(isAutoLogin);
	}

	private void setupViews() {
		login = (Button) findViewById(R.id.login);
		userNumInput = (EditText) findViewById(R.id.user_name);
		userPwdInput = (EditText) findViewById(R.id.user_password);
		dropDown = (ImageButton) findViewById(R.id.drop_down_button);
		autoLogin = (CheckBox) findViewById(R.id.login_quick_auto_login_button);

	}

	/**
	 * 登录按钮监听
	 */
	public void loginClicked(View v) {
		final String userNum = userNumInput.getText().toString();
		final String userPwd = userPwdInput.getText().toString();

		if (isUserNumberAndPasswordNull(userNum, userPwd)) {
			isAutoLogin();
			// 有网络时，发送异步Post请求
			if (NetworkUtils.isNetworkAvailable(this)) {
				requestLogin(userNum, userPwd);
			}
			// 无网络登陆时
			else {
				checkInputUserAndPwd(userNum, userPwd);
			}
		}
	}

	/**
	 * 发送用户名和密码，请求登录
	 * 
	 * @param userNumber
	 * @param userPassword
	 */
	private void requestLogin(String userNumber, String userPassword) {
		LoginTask task = LoginTask.newTask(LoginActivity.this, userNumber, userPassword);
		task.registerCallback(LoginActivity.this);
		task.execute();
	}

	/**
	 * 下拉按钮监听
	 */
	public void dropDownButtonClicked(View v) {
		if (!isDropDownButtonClicked) {
			dropDown.setBackgroundResource(R.drawable.btn_drop_down_selected);
			// 点击后的状态存进SharedPreference
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, true);
			SharedPreferenceUtil.saveData(LoginActivity.this, prefsMap);
			UserDao userDao = new UserDao(LoginActivity.this);
			ArrayList<UserBean> userList = new ArrayList<UserBean>();
			userList = userDao.getAllUser();
			showPopupWindow(userNumInput, userList);
		} else {
			dropDown.setBackgroundResource(R.drawable.btn_drop_down_normal);
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
			SharedPreferenceUtil.saveData(LoginActivity.this, prefsMap);
		}
	}

	/**
	 * 用户名历史的下拉菜单
	 * 
	 * @param view
	 * @param userList
	 */
	private void showPopupWindow(View view, ArrayList<UserBean> userList) {

		final DropDownAdapter adapter = new DropDownAdapter(LoginActivity.this, userList);
		// 一个自定义的布局，作为显示的内容
		View contentView = LayoutInflater.from(LoginActivity.this).inflate(R.layout.drop_down_listview, null);

		popupWindow = new PopupWindow(contentView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		// 设置SelectPicPopupWindow弹出窗体的宽
		popupWindow.setWidth(view.getWidth()+dropDown.getWidth());
        popupWindow.setHeight(view.getHeight());
		popupWindow.setFocusable(true);
		ListView dropDownListView = (ListView) contentView.findViewById(R.id.drop_down_listview);
		dropDownListView.setAdapter(adapter);
		// 点击外部，收起popupwindow
		popupWindow.setTouchInterceptor(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				dropDown.setBackgroundResource(R.drawable.btn_drop_down_normal);
				// 将下拉按钮的状态保存到SharedPreference
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
				SharedPreferenceUtil.saveData(LoginActivity.this, prefsMap);
				return false; // 这里如果返回true的话，touch事件将被拦截,拦截后,PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}
		});
		// 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
		popupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.white));
		popupWindow.showAsDropDown(view);

	}

	/**
	 * 登录请求返回结果处理
	 * 
	 * @param result
	 */
	public void handleLoginResponse(String result) {
		try {
			// 判断得到的数据是否为null
			if (!StringUtils.isEmptyOrStringNull(result)) {
				JSONObject jsonObject = new JSONObject(result);
				String loginMsg = jsonObject.getString(Common.JsonResult.MESSAGE);

				// 登陆成功
				if (loginMsg.equals(Common.JsonResult.LOGIN_SUCCESS)) {
					// 显示登录情况

					Toast.makeText(getApplicationContext(), R.string.tips_login_success, Toast.LENGTH_SHORT).show();
					LoginTask.saveData(LoginActivity.this, jsonObject);
					IntentUtils.jump(LoginActivity.this, HomeActivity.class);
					finish();
				} else if (loginMsg.equals(Common.JsonResult.LOGIN_FAIL)) {
					// 登录失败
					ToastUtils.show(LoginActivity.this, R.string.tips_login_fail);
					userNumInput.setText("");
					userPwdInput.setText("");
				}
			} else {
				String userNumber = userNumInput.getText().toString();
				String userPassword = userPwdInput.getText().toString();
				checkInputUserAndPwd(userNumber, userPassword);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 和本地数据库验证输入的用户名和密码是否匹配
	 * 
	 * @param userNumber
	 * @param userPassword
	 */
	public void checkInputUserAndPwd(String userNumber, String userPassword) {
		UserDao userDao = new UserDao(LoginActivity.this);
		UserBean userBean = userDao.getUserByUserNumber(userNumber);
		if (userBean != null) {
			if (userBean.getPassword().equals(userPassword)) {
				// 将当前登录的用户信息保存到SharedPreference
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.USER_ID, userBean.getId());
				prefsMap.put(Common.Prefs.USER_Name, userBean.getName());
				prefsMap.put(Common.Prefs.USER_NUMBER, userBean.getNumber());
				prefsMap.put(Common.Prefs.USER_PWD, userBean.getPassword());
				prefsMap.put(Common.Prefs.USER_ImageUrl, userBean.getImageUrl());
				SharedPreferenceUtil.saveData(LoginActivity.this, prefsMap);
				IntentUtils.jump(LoginActivity.this, HomeActivity.class);
				finish();
			} else {

				ToastUtils.show(LoginActivity.this, R.string.tips_login_password_error);
			}
		} else {

			ToastUtils.show(LoginActivity.this, R.string.tips_login_usernumber_nonentity);
		}
	}

	/**
	 * 判断用户名和密码是否为空
	 * 
	 * @param userNumber
	 * @param userPassword
	 * @return
	 */
	public boolean isUserNumberAndPasswordNull(String userNumber, String userPassword) {
		if (isUserNumEmpty()) {
			Toast.makeText(LoginActivity.this, "用户名未填写", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (isUserPwdEmpty()) {
			Toast.makeText(LoginActivity.this, "密码未填写", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	/**
	 * 保存获取的登录信息
	 * 
	 * @param jsonObject
	 */
	public static void saveData(Context context, JSONObject jsonObject) {
		try {
			if (jsonObject.getJSONObject(Common.JsonResult.RESULT_MAP) != null) {
				jsonObject = jsonObject.getJSONObject(Common.JsonResult.RESULT_MAP);
				if (jsonObject.getJSONObject(Common.JsonResult.LOGIN_USER) != null) {
					jsonObject = jsonObject.getJSONObject(Common.JsonResult.LOGIN_USER);
				}
			}
			// 1. 将JsonObject存入本地数据库
			UserBean userBean = new UserBean();
			userBean.fillAttributeByJson(jsonObject);
			UserDao userDao = new UserDao(context);
			userDao.insertOrUpdate(userBean);
			// 2. 将当前登录的用户信息保存到SharedPreference
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.USER_ID, userBean.getId());
			prefsMap.put(Common.Prefs.USER_Name, userBean.getName());
			prefsMap.put(Common.Prefs.USER_NUMBER, userBean.getNumber());
			prefsMap.put(Common.Prefs.USER_PWD, userBean.getPassword());
			prefsMap.put(Common.Prefs.USER_ImageUrl, userBean.getImageUrl());
			SharedPreferenceUtil.saveData(context, prefsMap);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 监听自动登陆按钮
	 */
	public void isAutoLogin() {
		Map<String, Object> userLoginInformation = new HashMap<String, Object>();
		// 监听自动登录checkBox是否被选中
		if (autoLogin.isChecked()) {
			// 将userNumberuserPassword保存到SharedPreference
			userLoginInformation.put(Common.Prefs.USER_NUMBER, userNumInput.getText().toString());
			userLoginInformation.put(Common.Prefs.USER_PWD, userPwdInput.getText().toString());
			userLoginInformation.put(Common.Prefs.IS_AUTO_LOGIN, true);
		} else {
			// 如果未选中则保持checkBox状态为未选中
			userLoginInformation.put(Common.Prefs.IS_AUTO_LOGIN, false);
		}
		SharedPreferenceUtil.saveData(LoginActivity.this, userLoginInformation);
	}

	private boolean isUserNumEmpty() {
		return StringUtils.isEmptyOrStringNull(userNumInput.getText().toString());
	}

	private boolean isUserPwdEmpty() {
		return StringUtils.isEmptyOrStringNull(userPwdInput.getText().toString());
	}

}
